package alg20250102;

public class Text {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        //先计算两个链表长度  长链表先走(len长 - len短)步 然后同时走 如果相等返回交点  否则返回null
        int lenA = 0, lenB = 0;
        ListNode curA = headA, curB = headB;
        while(curA != null){
            lenA++;
            curA = curA.next;
        }
        while(curB != null){
            lenB++;
            curB = curB.next;
        }
        curA = headA;
        curB = headB;
        //求差  长的先走
        int len = 0;
        if(lenA > lenB) {
            len = lenA - lenB;
            while(len > 0){
                curA = curA.next;
                len--;
            }
        }
        else {
            len = lenB - lenA;
            while(len > 0){
                curB = curB.next;
                len--;
            }
        }
        //同时走
        while(curA != null){
            if(curA == curB) return curA;
            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }
}
